//
//  ScanGoodListVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/11/11.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "ScanGoodListVC.h"
#import "BillAddPackageGoodModel.h"
#import "ScanGoodListCell.h"
#import "WCQRCodeScanningVC.h"
#import "ScanGoodErrorAlertView.h"
#import "ScanGoodDetailVC.h"

@interface ScanGoodListVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <BillAddPackageGoodModel *>*dataArray;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation ScanGoodListVC

-(NSMutableArray <BillAddPackageGoodModel *>*)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - self.bottomView.nim_height - NaviHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakself requestForList];
        }];
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
             titleStr:@""
            detailStr:@""];
    }
    return _tableView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
        [nextBtn setBackgroundColor:Color_ThemeColor];
        nextBtn.layer.masksToBounds = YES;
        nextBtn.layer.cornerRadius = 6;
        [nextBtn setTitle:@"确认提交" forState:0];
        [nextBtn setTitleColor:HexColor(0xffffff) forState:0];
        nextBtn.titleLabel.font = BoldFontOfSize(16);
        [nextBtn addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:nextBtn];
    }
    return _bottomView;
}

- (void)sureClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定提交吗？" preferredStyle:UIAlertControllerStyleAlert];
    __weak_self;
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself.rt_navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"已添加货物列表";
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableView];
    [self requestForList];
    if (!self.isJieChu) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 96, 30)];
        [btn setTitle:@"扫码绑定" forState:0];
        [btn setTitleColor:HexColor(0xffffff) forState:0];
        btn.backgroundColor = Color_ThemeColor;
        btn.layer.cornerRadius = 15;
        btn.titleLabel.font = BoldFontOfSize(14);
        [btn addTarget:self action:@selector(scanClick) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestForList) name:ReceiptDeliveryRefreshScanAddGoodList object:nil];
}

- (void)scanClick {
    WCQRCodeScanningVC *vc = [WCQRCodeScanningVC new];
    __weak_self;
    vc.returnBlock = ^(id dic) {
        /*
         {
             num = PB202010293820001;
             "pk_id" = 8;
             type = normal;
         }
         {
             num = ZB202010149459;
             "rv_id" = 8;
             type = revolve;
         }
         */
        [weakself requestForScanAdd:dic];
    };
    [self.rt_navigationController pushViewController:vc animated:YES];
}

- (void)requestForScanAdd:(id)dd {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if ([[dd objectForKey:@"type"] isEqualToString:@"normal"]) {
        [dic setObject:[dd objectForKey:@"num"] forKey:@"pk_num"];
    }else {
        [dic setObject:[dd objectForKey:@"num"] forKey:@"origina_sn"];
    }
    [dic setObject:[dd objectForKey:@"type"] forKey:@"type"];
    [dic setObject:self.wa_id forKey:@"wa_id"];
    [HttpRequest PostWithApi:ReceiptDeliveryBillAddPackageScan params:dic progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            NSInteger status_type = [[responseObject objectForKey:@"status_type"] integerValue];
            ScanGoodErrorAlertView *alert = [ScanGoodErrorAlertView new];
            alert.content1 = [responseObject objectForKey:@"name"];
            if (status_type == 1101) {
                //当前扫码的货物型号与运单中的货物型号不符
                alert.content2 = [responseObject objectForKey:@"good_type"];
                alert.type = ScanGoodErrorTypeGoodError;
                [alert showInView:MAIN_WINDOW];
            }else if (status_type == 1102) {
                //当前运单中没有此货物，请取消或重新扫描
                alert.content2 = [responseObject objectForKey:@"good_type"];
                alert.type = ScanGoodErrorTypeNoGood;
                [alert showInView:MAIN_WINDOW];
            }else if (status_type == 1103) {
                //此箱已被绑过
                alert.content2 = [responseObject objectForKey:@"good_type"];
                alert.type = ScanGoodErrorTypeBoxError;
                [alert showInView:MAIN_WINDOW];
            }else if (status_type == 1104) {
                //货物中的件数已超过运单中件数
                alert.content2 = [responseObject objectForKey:@"pnum"];
                alert.type = ScanGoodErrorTypeCountError;
                [alert showInView:MAIN_WINDOW];
            }else {
                //扫码添加成功
                BillAddPackageGoodModel *model = [BillAddPackageGoodModel mj_objectWithKeyValues:responseObject];
                [self.dataArray enumerateObjectsUsingBlock:^(BillAddPackageGoodModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj.g_id isEqualToString:model.g_id]) {
                        obj.already_num = model.already_num;
                        obj.already_jnum = model.already_jnum;
                    }
                }];
                [self.tableView reloadData];
                [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"添加成功"];
            }
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)requestForList {
    [HttpRequest PostWithApi:ReceiptDeliveryBillAddPackageScanGoodList params:@{@"wa_id":self.wa_id} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [self.dataArray removeAllObjects];
            self.dataArray = [BillAddPackageGoodModel mj_objectArrayWithKeyValuesArray:responseObject];
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ScanGoodListCell *cell = [ScanGoodListCell ScanGoodListCellWithTableView:tableView];
    BillAddPackageGoodModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    __weak_self;
    cell.operationBlock = ^{
        ScanGoodDetailVC *vc = [ScanGoodDetailVC new];
        vc.g_id = model.g_id;
        vc.wa_id = weakself.wa_id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ScanGoodListCell *cell = [ScanGoodListCell ScanGoodListCellWithTableView:tableView];
    BillAddPackageGoodModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
